package com.javabasic.algorithm.leetcode;

import java.util.HashMap;


public class ThreeSumClosest {

    public int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            if (map.containsKey(nums[i])) {
                map.put(nums[i],map.get(nums[i])+1);
            } else {
                map.put(nums[i],1);
            }
        }
        int count = 3;
        int result = 0;
        int temp1 = 0, temp2 = 0, temp = 0;

        if (map.containsKey(target)) {
            temp = map.get(target);
            if (temp >= count) temp = count;
            count -= temp;
            result += target*temp;
        }
        for (int  i = 1; ; i++) {
            if (count > 0 && map.containsKey(target+i)) {
                temp1 = map.get(target+i);
                if (temp1 >= count) temp1 = count;
                count -= temp1;
                result += (target+i)*temp1;
            }
            if (count > 0 && map.containsKey(target-i)) {
                temp2 = map.get(target-i);
                if (temp2 >= count) temp2 = count;
                count -= temp2;
                result += (target-i)*temp2;
            }
            if (count == 0) {
                break;
            }
        }
        return result;
    }
}
